#!/usr/bin/env python
import os, logging
from application.settings import DEBUG


if __name__ == '__main__':

    if len(os.sys.argv) > 1 and os.sys.argv[1].lower() == 'debug':
        DEBUG = True
        argv = [os.sys.argv[0]]
        os.sys.argv = argv
    else:
        argv = os.sys.argv

    release = len(argv) < 2
    
    if not DEBUG:
        #  in the release version of apscheduler, set login level to warning
        aps_logger = logging.getLogger('apscheduler')
        aps_logger.setLevel(logging.WARNING)
        
    # start websockify 
    if not os.environ.get('RUN_MAIN') and release:
        import subprocess, signal
        child = subprocess.Popen([
            "python",
            "-m",
            "websockify",
            '--token-plugin=BaseTokenAPI',
            '--token-source=http://localhost:8000/virt/display/info/?token=%s',
            '8009'
            ], cwd=os.path.dirname(os.environ.get("PWD")))
        def exit_signal(signal):
            child.send_signal(signal)
            os.sys.exit(0)
        signal.signal(signal.SIGINT, exit_signal)
        signal.signal(signal.SIGTERM, exit_signal)
    # run django and channels use daphne
    if(release):
        from daphne.cli import CommandLineInterface
        import sys
        sys.argv = ["run.py", "application.asgi:application"]
        print(sys.argv[0])
        sys.exit(CommandLineInterface.entrypoint())
    else:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings')
        try:
            from django.core.management import execute_from_command_line
        except ImportError as exc:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            ) from exc
        execute_from_command_line(argv)